<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 消息提示 区域 -->
       <el-alert title="添加商品信息" type="info" show-icon center> </el-alert>
       <!-- 步骤提示 区域 -->
       <el-steps :space="200" :active="activeIndex - 0 " finish-status="success" align-center>
          <el-step title="基本信息"></el-step>
          <el-step title="商品参数"></el-step>
          <el-step title="商品属性"></el-step>
          <el-step title="商品图片"></el-step>
          <el-step title="商品内容"></el-step>
          <el-step title="完成"></el-step>
        </el-steps>
        <!-- tab栏 切换 -->
      <el-form :model="addGoodsForm" :rules="addGoodsRules" ref="addGoodsRef" label-width="70px" label-position="top">
        <el-tabs :tab-position="'left'" v-model="activeIndex" :before-leave="beforLeaveTab"
        @tab-click="tabClicked">
          <el-tab-pane label="基本信息" name="0">
              <el-form-item label="商品名称" prop="goods_name">
                <el-input v-model="addGoodsForm.goods_name"></el-input>
              </el-form-item>
              <el-form-item label="商品价格" prop="goods_price" type="number">
                <el-input v-model="addGoodsForm.goods_price"></el-input>
              </el-form-item>
              <el-form-item label="商品重量" prop="goods_weight" type="number">
                <el-input v-model="addGoodsForm.goods_weight"></el-input>
              </el-form-item>
              <el-form-item label="商品数量" prop="goods_number">
                <el-input v-model="addGoodsForm.goods_number"></el-input>
              </el-form-item>
              <el-form-item label="商品分类" prop="goods_cat">
                <!-- options 可选项数据源，键名可通过 Props 属性配置 -->
                <el-cascader v-model="addGoodsForm.goods_cat" :options="goodsCateList" 
                  :props="cascaderProps" @change="handleChange" clearable
                  ></el-cascader>
              </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="item1" v-for="(item1, index) in item.attr_vals" :key="index" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove" 
              :headers="headerObj"
              :on-success="handleSuccess"

              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑区域 -->
            <quill-editor v-model="addGoodsForm.goods_introduce"/>
            <el-button type="primary" class="addbtn" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 预览图片对话框 -->
    <el-dialog title="预览图片" :visible.sync="picVisible" width="30%">
        <img :src="priviewSrc" class="priviewPic" />
    </el-dialog>

  </div>
</template>

<script>
export default {
  data(){
    return{
      // 激活的步骤
      activeIndex:'0',
      // 添加商品 表单数据
      addGoodsForm:{
        goods_name:'',
        goods_price:0,
        goods_number:0,
        goods_weight:0,
        goods_cat:[],
        pics:[],
        goods_introduce:'',
        attrs:[]
      },
      // 添加商品表单验证规则
      addGoodsRules:{
         goods_name:[
          { required: true, message: '请输入商品名称', trigger: 'blur' }
         ],
         goods_price:[
          { required: true, message: '请输入商品价格', trigger: 'blur' }
         ],
         goods_number:[
          { required: true, message: '请输入商品数量', trigger: 'blur' }
         ],
         goods_weight:[
          { required: true, message: '请输入商品重量', trigger: 'blur' }
         ],
         goods_cat:[
          { required: true, message: '请选择商品分类', trigger: 'blur' }
         ],
      },
      // 商品分类 数组
      goodsCateList:[],
      // 级联选择器配置选项
      cascaderProps:{
        expandTrigger:'hover',
        value:"cat_id",
        label:"cat_name",
        children:"children"
      },
      // 动态参数 数据
      manyTableData:[],
      // 静态属性 数据
      onlyTableData:[],
      // 图片上传url地址
      uploadURL:"http://127.0.0.1:8888/api/private/v1/upload",
      // upload上传图片请求 配置项
      headerObj:{
        Authorization: window.sessionStorage.getItem("token")
      },
      // 预览图片src地址
      priviewSrc:'',
      // 控制预览图片 展示
      picVisible:false,
    }
  },
  created(){
    this.getGoodsList();
  },
  methods:{
    // 添加商品 方法
    async addGoods(){
      // 表单提交的预校验
      this.$refs.addGoodsRef.validate(async valid => {
        if(!valid) return this.$message.error("表单提交失败");
        // 将表单数据深拷贝为form,对form的 goods_cat 操作
        const form = _.cloneDeep(this.addGoodsForm);
        // 将form中的 goods_cat 转换为以都好分割的字符串
        form.goods_cat = form.goods_cat.join(',');
        // 处理动态属性
        this.manyTableData.forEach( item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          };
          this.addGoodsForm.attrs.push(newInfo);
        });
        // 处理静态参数
        this.onlyTableData.forEach( item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          };
          this.addGoodsForm.attrs.push(newInfo);
        });
        form.attrs = this.addGoodsForm.attrs;
        // 发起网络请求，添加新用户
        const { data: res } = await this.$http.post("goods", form );
        if(res.meta.status !== 201){
          this.$message.error("添加商品失败！");
        }else{
          this.$message.success("添加商品成功！");
          this.$router.push('/goods');
        }     
    });
    },
    // 获取商品分类列表数据 方法
    async getGoodsList(){
     const { data: res } = await this.$http.get("categories");
     if(res.meta.status !== 200)  return this.$message.error("获取商品分类列表失败");
     this.goodsCateList = res.data;
    //  console.log(this.goodsCateList);
    },
    // 监听级联选择器 改变事件
    handleChange(){
      if(this.addGoodsForm.goods_cat.length !== 3){
        this.addGoodsForm.goods_cat = [];
      }
    },
    // 切换标签页事件
    beforLeaveTab(newName,oldNamw){
      // 只有选中了三级标签，才能切换标签页
      if(this.addGoodsForm.goods_cat.length !== 3){
        return false;
      }
    },
    // 点击tab事件
    async tabClicked(){
      if(this.activeIndex === '1'){
        const { data: res } = await this.$http.get(`categories/${ this.cateId }/attributes`,
        { params:{ sel: 'many'}});
        if(res.meta.status !== 200) return this.$message.error("获取失败");
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ');
        });
        this.manyTableData = res.data;
      }else if(this.activeIndex === '2'){
        const { data: res } = await this.$http.get(`categories/${ this.cateId }/attributes`,
        { params:{ sel: 'only'}});
        if(res.meta.status !== 200) return this.$message.error("获取失败");
        // res.data.forEach(item => {
        //   item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ');
        // });
        this.onlyTableData = res.data;
        // console.log(this.onlyTableData);
      }
    },
    // 预览图片 方法
    handlePreview(file){
      this.priviewSrc = file.response.data.url;
      this.picVisible = true;

    },
    // 移除图片 方法
    handleRemove(file){
      console.log(file);
      // 1. 获取要移除图片的路径
      const picPath = file.response.data.tmp_path;
      // 2. 从pics数组中找到该文件路径对应的索引值,findIndex返回索引值
      const i = this.addGoodsForm.pics.findIndex( x => x.pic === picPath);
      // 3. 删除为 i 的这一项
      this.addGoodsForm.pics.splice(i, 1);
    },
    // 图片上传成功 钩子
    handleSuccess(response){
      const picInfo = { pic:response.data.tmp_path };
      // 将图片上传后的临时路径保存到 添加商品信息表单中
      this.addGoodsForm.pics.push(picInfo);
      // console.log(this.addGoodsForm.pics); 
    },

  },
  computed:{
    // 商品分类id
    cateId(){
      if(this.addGoodsForm.goods_cat.length === 3){
        return this.addGoodsForm.goods_cat[2];
      }
      return null;
    }
  }
}
</script>

<style lang="less" scoped>
.el-steps{
  margin: 15px 0;
  /deep/.el-step__title{
  font-size: 12px;
}
}
.el-checkbox{
  margin: 0 10px 0 0;
}
.priviewPic{
  width: 100%;
}
/deep/.ql-editor{
  min-height: 300px;
}
.addbtn{
  margin-top: 15px;
}
</style>